# -*- coding: utf-8 -*-

import urllib
import md5
import time

from django.utils import simplejson

from google.appengine.api import urlfetch
from google.appengine.api.urlfetch_errors import *

# All helper and utility functions for alisoft SIP
class AliSoftAPI:
    mainurl = "http://sip.alisoft.com/sip/rest"
    appid = "21733"
    version = "1.0"
    sessionid = "4b522830f9c211dd8280eb5a34796bba"
    secret = "4b522830f9c211dd8280eb5a34796bba"
    instanceid = ""
    target = ""
    token = ""
    userid = ""

    def reqAndRsp(self, req):
        result = self.reqAndRspPlain(req)
        return simplejson.loads(result.content)
    
    def reqAndRspPlain(self, req):
        ## sign request
        req['sip_sign'] = self.__sign__(req)        
        form_data = urllib.urlencode(req)
        result = urlfetch.fetch(url=self.mainurl,
                                payload=form_data,
                                method=urlfetch.POST,
                                headers={'Content-Type': 'application/x-www-form-urlencoded'})
        return result
        
    def getSIPReq(self, apiname):
        req = {'sip_appkey': self.appid,
               'sip_apiname': 'alisoft.validateUser',
               'sip_sessionid': self.sessionid,
               'sip_service_command': apiname,
               'sip_timestamp': self.__now__()}
        return req
        
    def getReq(self, apiname):
        req = {'sip_appkey':self.appid, 'v':self.version}
        req['sip_apiname'] = apiname
        req['sip_sessionid'] = self.sessionid
        req['sip_timestamp'] = self.__now__()
        return req    

    def __now__(self):
        stime = None
        if(time.timezone == 0):
            gmtimefix = 28800
            stime = time.gmtime(gmtimefix + time.time())
        else:
            stime = time.localtime()
        strtime = time.strftime( '%Y-%m-%d %X', stime)
        #Log.debug("time:" + strtime)
        return strtime  
    

    def __sign__(self, params):
        encrypt = md5.new()
        encrypt.update(self.secret)
        for k, v in sorted(params.items()):
            encrypt.update(k)
            encrypt.update(v)
        return encrypt.hexdigest().upper()
        #signSrc = self.apiConfig.secret + ''.join(["%s%s" % (k, v) for k, v in sorted(params.items())])
        #return md5.new(signSrc).hexdigest().upper()              
    
